package copy;

import java.io.*;

/**
 * @projectName: com.xiayuanxing.designPattern
 * @className: DeepProtoType
 * @author: xiayuanxing
 * @description: TODO
 * @date: 2021/12/18 16:53
 * @version: 1.0
 */
public class DeepProtoType implements Serializable,Cloneable {

    //string 属性
    public String name;

    //引用类型
    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType(){
        super();
    }


    /**
     * @author xiayuanxing
     * @description 深拷贝实现方式一：使用clone()方法
     * @date 2021/12/18 16:55
     */
    @Override
    protected Object clone() throws CloneNotSupportedException{
        Object deep = null;
        //对基本数据类型的克隆
        deep = super.clone();
        //对引用数据类型进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }


    /**
     * @author xiayuanxing
     * @description 深拷贝实现方式一：使用对象序列化的方式
     * @date 2021/12/18 16:58
     */
    public Object deepClone(){

        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //当前这个对象是以对象流的方式输出
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObj = (DeepProtoType) ois.readObject();
            return copyObj;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            //关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            }catch (Exception e2){
                System.out.println(e2.getMessage());
            }
        }

    }


}
